package tool

import (
	"archive/zip"
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"github.com/xuri/excelize/v2"
	"io/ioutil"
	"os"
	"os/exec"
	"path"
	"strings"
)

type FileTool struct {
}
type FileUpload struct {
	Name string `json:"name"`
	File string `json:"file"`
}

func (this FileTool) CreateDirForPath(Path string) error {
	Path = path.Clean(Path)
	pathStr := path.Dir(Path)
	pathStr = strings.ReplaceAll(pathStr, "\\", "/")
	pathSlice := strings.Split(pathStr, "/")
	start := ""
	for index, dir := range pathSlice {
		if index == 0 {
			continue
		}
		start = start + "/" + dir
		os.Mkdir(path.Dir(start), 0777)
	}
	return os.Mkdir(path.Dir(Path), 0777)
}

func CreateDirForPath(Path string) error {
	Path = path.Clean(Path)
	pathStr := path.Dir(Path)
	pathStr = strings.ReplaceAll(pathStr, "\\", "/")
	pathSlice := strings.Split(pathStr, "/")
	start := ""
	for index, dir := range pathSlice {
		if index == 0 {
			continue
		}
		start = start + "/" + dir
		os.Mkdir(path.Dir(start), 0777)
	}
	return os.Mkdir(path.Dir(Path), 0777)
}

func ReadFile(path string) []byte {
	fileContent, err := os.ReadFile(path)
	if err != nil {
		return fileContent
	}
	return fileContent
}

func (this FileTool) GetExt(Path string) string {
	return path.Ext(Path)
}

func ReadExcel(path string) ([][]string, error) {
	f, err := excelize.OpenFile(path)
	if err != nil {
		return nil, err
	}
	f.GetActiveSheetIndex()
	name := f.GetSheetName(f.GetActiveSheetIndex())
	cols, err := f.Cols(name)
	if err != nil {
		return nil, err
	}
	var data = make([][]string, 0)
	for cols.Next() {
		col, err := cols.Rows()
		if err != nil {
			return nil, err
		}
		var row = make([]string, 0)
		for _, rowCell := range col {
			row = append(row, rowCell)
		}
		data = append(data, row)
	}
	return data, nil
}

func GetCurrentPath() string {
	s, _ := exec.LookPath(os.Args[0])
	i := strings.LastIndex(s, "\\")
	return s[0 : i+1]
}

func FileExist(path string) bool {
	_, err := os.Lstat(path)
	return !os.IsNotExist(err)
}

func AppRoot() string {
	return web.AppConfig.DefaultString("Root", "")
}

func CreateFile(filePath string, content []byte) {
	//数据库配置
	if !FileExist(path.Dir(filePath)) {
		err := CreateDirForPath(filePath)
		if err != nil {
			println("创建路径", err.Error())
		}
	}
	err1 := ioutil.WriteFile(filePath, content, 0777)
	if err1 != nil {
		println("写入文件", err1.Error())
	}
}

type Zipper struct {
	Path   string
	Name   string
	Target string
}

func CreateZip(fileName string, files ...*Zipper) (string, bool) {
	root := web.AppConfig.DefaultString("Root", "")
	dir := GetDate("")
	zipFilePath := fmt.Sprintf("%s/static/var/tmp/%s/%s.zip", root, dir, fileName)
	CreateDirForPath(zipFilePath)
	zipFile, err := os.Create(zipFilePath)
	if err != nil {
		return err.Error(), false
	}
	zipWriter := zip.NewWriter(zipFile)
	defer zipWriter.Close()
	for _, file := range files {
		fileContent := ReadFile(root + file.Path)
		if len(fileContent) == 0 {
			return "文件未找到" + file.Name, false
		}
		//ext := path.Ext(file.Path)
		fwrite, err := zipWriter.Create(file.Name)
		if err != nil {
			return "文件创建时发生错误:" + file.Name, false
		}
		_, err = fwrite.Write(fileContent)
		if err != nil {
			return "文件写入时发生错误:" + file.Name, false
		}
	}
	return zipFilePath[len(root):], true
}
